// src/store/user.ts
import { getUserInfo, loginApi, logOut } from '@/apis/login'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import Storage from '@/utils/storage';

export const useUserStore = defineStore(
  'user',
  () => {
    const count = ref(0)
    const userInfo = ref()
    const token = ref<string | null>()

    const increment = () => {
      count.value++
    }
    const decrement = () => {
      count.value--
    }
    const reset = () => {
      count.value = 0
    }
    const setUniToken = (token: string) => {
      token = token
    }
    const resetUniToken = () => {
      token.value = null
    }

    const loginFun = async (params: Object): Promise<any> => {
      try {
        const data = await loginApi(params)
        const { accessToken, tokenType } = data as any
        // token保存在两个地方一个是全局Storage实例中，一个在pinia
        Storage.setCache('token', `${tokenType} ${accessToken}`)
        setUniToken(`${tokenType} ${accessToken}`)
        !!accessToken && afterLoginAction()
      } catch (error) {
        return Promise.reject(error)
      }
    }

    const afterLoginAction = async() => {
      const info = await getUserInfo();
      // console.log('userinfo', info)
      userInfo.value  = info;
      uni.switchTab({ url: '/pages/index/index' });
    }

    const logOutFun = async() => {
      const ret = await logOut();
      Storage.clearCache();
      resetUniToken();
      uni.navigateTo({url: '/pages/login/login'})
    }

    return {
      count,
      token,
      userInfo,
      decrement,
      increment,
      reset,
      loginFun,
      getUserInfo,
      logOutFun,
    }
  },
    {
        unistorage: true, // 开启后对 state 的数据读写都将持久化
    }
)
